var request   = require('request');
var url       = require('url');

var req = function(options, callback) {
  //检察数据格式
  options.json = options.json === undefined ? true : options.json;

  var client = options.client;
  if (client.headers) {
    options.headers = {};
    options.headers['User-Agent'] = client.headers['User-Agent'];
  }

  var urlObj = url.parse(options.uri);
  if (process.env.NODE_ENV === 'production') {
    var cookies = client.cookies;
    var apiSever = cookies.apiSever;
    if (apiSever) {
      urlObj.host = apiSever.host + ':' + apiSever.port;
      urlObj.port = apiSever.port;
      urlObj.hostName = apiSever.host;
      var uri = url.format(urlObj);
      options.uri = uri;
    }
  }

  if (client.cookies) {
    var cookieUrl = urlObj.protocol + '//' + urlObj.host;
    var j = request.jar();
    for (var key in client.cookies) {
      if (client.cookies.hasOwnProperty(key)) {
        var cookie = request.cookie(key + '=' + client.cookies[key]);
        j.setCookie(cookie, cookieUrl);
      }
    }
  }

  delete options.client;

  request(options, function(error, response, data) {
    // if (!error && typeof data === 'string') {
    //   error = {
    //     message: data,
    //     url: options.uri
    //   };
    // }
    callback(error, response, data);
    });
}

req.getJSON = function(options, callback) {
  options.method = 'GET';
  req(options, callback);
}

req.postJSON = function(options, callback) {
  options.method = 'POST';
  options.body = options.body || {};
  req(options, callback);
}

module.exports = req;